
package com.wobaby.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import com.wobaby.util.config.Config;

// Referenced classes of package com.wobaby.util:
//            RenditionUncheckedException, ReflectionSupport

public class RenditionUtil
{

    public RenditionUtil()
    {
    }

    public static Collection intersect(Collection a, Collection b)
    {
        ArrayList al = new ArrayList();
        if(a == null || a.size() == 0 || b == null || b.size() == 0)
        {
            return al;
        } else
        {
            al.addAll(a);
            al.retainAll(b);
            return al;
        }
    }

    public static Collection union(Collection a, Collection b)
    {
        ArrayList al = new ArrayList();
        if(a != null)
            al.addAll(a);
        if(b != null)
        {
            Iterator it = b.iterator();
            do
            {
                if(!it.hasNext())
                    break;
                Object o = it.next();
                if(!al.contains(o))
                    al.add(o);
            } while(true);
        }
        return al;
    }

    public static final boolean eq(Object left, Object right)
    {
        if(left == null && right == null)
            return true;
        if(left == null || right == null)
            return false;
        if((left instanceof Date) && (right instanceof Date))
            return ((Date)left).getTime() / 1000L == ((Date)right).getTime() / 1000L;
        else
            return left.equals(right);
    }

    public static boolean eqw(String left, String right)
    {
        if(left == null)
            left = "";
        if(right == null)
            right = "";
        return left.trim().equals(right.trim());
    }

 /*   public static String toString(Object o)
    {
        StringBuffer buf = new StringBuffer();
        buf.append("[");
        Class classObj = o.getClass();
        Field fields[] = classObj.getDeclaredFields();
        boolean atLeastOne = false;
        for(int i = 0; i < fields.length; i++)
        {
            Field curField = fields[i];
            String fieldName = curField.getName();
            java.lang.reflect.Method method = ReflectionSupport.getGetterMethod(classObj, fieldName);
            if(method == null)
                continue;
            Object returnValue = ReflectionSupport.invoke(o, method, null);
            if(atLeastOne)
                buf.append(", ");
            if(returnValue == null)
                buf.append(fieldName).append("=").append("null");
            else
                buf.append(fieldName).append('=').append(returnValue.toString());
            atLeastOne = true;
        }

        buf.append("]");
        return buf.toString();
    }*/

    public static ArrayList arrayToList(Object array[])
    {
        ArrayList returnValue = new ArrayList(array.length);
        for(int i = 0; i < array.length; i++)
            returnValue.add(array[i]);

        return returnValue;
    }

    public static ArrayList setToList(Set set)
    {
        ArrayList returnValue = new ArrayList(set.size());
        for(Iterator it = set.iterator(); it.hasNext(); returnValue.add(it.next()));
        return returnValue;
    }

    public static boolean isInteractiveUserThread()
    {
        return Thread.currentThread().getName().indexOf("Thread-TaskID") == -1;
    }

    public static Properties stringToProperties(String data)
    {
        Properties p = new Properties();
        if(data == null)
            return p;
        try
        {
            p.load(new ByteArrayInputStream(data.getBytes()));
        }
        catch(IOException io)
        {
            throw new RenditionUncheckedException("Exception in stringToProperties", io);
        }
        return p;
    }

    public static String propertiesToString(Properties p)
    {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        try
        {
            p.store(bo, null);
        }
        catch(IOException io)
        {
            throw new RenditionUncheckedException("Exception in propertiesToString", io);
        }
        return new String(bo.toByteArray());
    }

    private static void initInet()
    {
        if(mInetAddr == null)
            try
            {
                mInetAddr = InetAddress.getLocalHost();
                mHostname = mInetAddr.getHostName();
                mIpAddress = mInetAddr.getHostAddress();
                mCanonical = mInetAddr.getCanonicalHostName();
            }
            catch(UnknownHostException ex)
            {
                mHostname = "localhost";
                mIpAddress = "localhost";
                mCanonical = "localhost";
            }
    }

    public static String getServerURL()
    {
        return getServerURL(true);
    }

    public static String getServerURL(boolean useHttps)
    {
        initInet();
        StringBuffer buf = new StringBuffer(64);
        if(useHttps)
            buf.append("https://");
        else
            buf.append("http://");
        String addressFormat = Config.getConfig().get("webui/email_report/address", null);
        if(addressFormat == null)
            buf.append("localhost");
        else
        if("hostname".equals(addressFormat))
            buf.append(mHostname);
        else
        if("ipaddress".equals(addressFormat))
            buf.append(mIpAddress);
        else
        if("canonical".equals(addressFormat))
            buf.append(mCanonical);
        else
            buf = new StringBuffer(addressFormat);
        buf.append("/");
        return buf.toString();
    }

    public static String getServerInstallDir()
    {
        String dir = Config.getConfig().get("install/dir", null);
        if(dir == null)
            throw new RenditionUncheckedException("Could not find install dir. Please check your 'install/dir' configuration in appserver.rcx file");
        else
            return dir;
    }

    public static String getResourceDir()
    {
        return getServerInstallDir() + File.separator + "resource";
    }

    public static boolean arrayContains(Object array[], Object needle)
    {
        if(array == null || array.length == 0)
            return false;
        if(!array[0].getClass().equals(needle.getClass()))
            return false;
        for(int i = 0; i < array.length; i++)
            if(needle.equals(array[i]))
                return true;

        return false;
    }

    public static String getCodeSourceLocation(Class cls)
    {
        if(cls.getProtectionDomain().getCodeSource() != null)
            return cls.getProtectionDomain().getCodeSource().getLocation().getFile();
        else
            return null;
    }

    public static synchronized int getUniqueInt()
    {
        UniqueInt++;
        if(UniqueInt == 0x5f5e100)
            UniqueInt = 1000;
        return UniqueInt;
    }

    private static InetAddress mInetAddr = null;
    private static String mHostname = null;
    private static String mIpAddress = null;
    private static String mCanonical = null;
    private static int UniqueInt = 1000;

}